<template>
  <div class="flex flex-col h-full p-4">
    <!-- Alert Container with white background -->
    <div class="flex-1 flex flex-col bg-white rounded-lg shadow p-6 min-h-0">
      <!-- Filter section -->
      <div class="mb-6">
        <div class="mb-4">
          <CustomTabs
            v-model="activeTab"
            :tabs="tabs"
            @change="handleTabChange"
          />
        </div>

        <div class="flex items-center gap-4">
          <el-input
            v-model="filters.alertCode"
            placeholder="Alert code/SN"
            clearable
            class="w-60!"
            @keyup.enter="searchAlerts"
            @clear="searchAlerts"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-input
            v-model="filters.systemId"
            placeholder="System ID/System name"
            clearable
            class="w-60!"
            @keyup.enter="searchAlerts"
            @clear="searchAlerts"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="→"
            start-placeholder="2020-11-08"
            end-placeholder="2020-12-23"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="w-64! grow-0!"
            @change="searchAlerts"
          />

          <el-select
            v-model="filters.deviceModel"
            placeholder="All device model"
            clearable
            class="w-60!"
            @change="searchAlerts"
          >
            <el-option
              v-for="item in deviceModelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>

          <div class="flex ml-auto">
            <el-button type="default" @click="resetFilters">Reset</el-button>
            <el-button type="primary" @click="searchAlerts">Search</el-button>
          </div>
        </div>
      </div>

      <!-- Table section with loading/empty/error -->
      <PageState
        :loading="loading"
        :error-message="errorMessage"
        :has-data="displayedAlertList.length > 0"
        @retry="retryFetch"
      >
        <AlertTable
          :alert-data="displayedAlertList"
          :pagination="pagination"
          :show-status-column="activeTab === 'All'"
          @page-change="handleCurrentChange"
          @size-change="handleSizeChange"
          @detail="showDetails"
          class="flex-1"
        />
      </PageState>
    </div>

    <!-- Alert Details Dialog -->
    <el-dialog
      v-model="dialogVisible"
      title="Alert Details"
      width="800px"
      :before-close="handleClose"
      custom-class="alert-details-dialog"
    >
      <AlertDetail :alert-detail="alertDetails" />

      <template #footer>
        <span class="flex justify-end">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false"
            >OK</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, watch } from "vue";
import { Search } from "@element-plus/icons-vue";
import { type AlertItem } from "./data";
import AlertTable from "./components/AlertTable.vue";
import AlertDetail from "./components/AlertDetail.vue";
import CustomTabs from "@/components/CustomTabs";
import { alertApi } from "@/api/business";
import { getToken } from "@/utils/cache";
import PageState from "@/components/base/PageState.vue";

// Define filters
const activeTab = ref("Active");
const dateRange = ref<[string, string] | []>([]);
const filters = reactive({
  alertCode: "",
  systemId: "",
  deviceModel: "All device model"
});

// 标签配置
const tabs = [
  { name: "All", label: "All" },
  { name: "Active", label: "Active" },
  { name: "Historical", label: "Historical" }
];

// Device model options（动态：来源于接口返回的 product 字段，去重）
const deviceModelOptions = ref<Array<{ value: string; label: string }>>([
  { value: "All device model", label: "All device model" }
]);

// 存储所有可用的设备型号（用于保持完整的选项列表）
const allAvailableDeviceModels = ref<Set<string>>(new Set());

// Pagination
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// Alert data
const allAlerts = ref<AlertItem[]>([]);
const activeAlerts = ref<AlertItem[]>([]);
const historicalAlerts = ref<AlertItem[]>([]);

// 将后端数据项映射为 AlertItem
const mapToAlertItem = (x: any): AlertItem => {
  return {
    id: String(x.id ?? x.alertId ?? ""),
    alertCode: String(x.alertCode ?? x.code ?? ""),
    alertName: String(x.alertName ?? x.name ?? ""),
    deviceName: String(x.deviceName ?? x.systemName ?? ""),
    sn: String(x.serialNumber ?? x.sn ?? ""),
    product: String(x.product ?? x.deviceModel ?? ""),
    faultyModule: String(x.faultyModule ?? x.modelModule ?? ""),
    systemName: String(x.systemName ?? x.system ?? ""),
    systemId: String(x.systemId ?? x.sid ?? ""),
    occurrences: Number(x.occurrences ?? x.occurCount ?? 0),
    status: String(x.status ?? "active") === "resolved" ? "resolved" : "active",
    occurrenceTime: String(x.occurrenceTime ?? x.occurTime ?? x.occurtime ?? x.occuranceTime ?? ""),
    recoveryTime: x.recoveryTime ? String(x.recoveryTime) : null,
    deviceModel: String(x.deviceModel ?? x.model ?? ""),
    possibleReason: String(x.possibleReason ?? x.reason ?? ""),
    suggestions: (() => {
      if (Array.isArray(x.suggestions)) return x.suggestions;
      const raw =
        typeof x.suggestions === "string"
          ? x.suggestions
          : typeof x.suggestion === "string"
          ? x.suggestion
          : "";
      if (!raw) return [];
      return raw
        .split(/[,，;；。\n]/)
        .map((s: string) => s.trim())
        .filter((s: string) => s);
    })()
  };
};

// 组装查询参数
const buildQueryParams = () => {
  const params: any = {
    page: pagination.currentPage,
    limit: pagination.pageSize,
    // API 文档：status 0:All和Active, 1:Historical
    faultStatus: activeTab.value === "Historical" ? 1 : 0,
    // 合并搜索：后端可同时匹配 code 或 sn
    search: (filters.alertCode || "").trim() || undefined,
    // API 文档：system 可传 system name 和 system id
    system: (filters.systemId || "").trim() || undefined,
    // API 文档：product 产品
    product:
      filters.deviceModel && filters.deviceModel !== "All device model"
        ? filters.deviceModel
        : undefined,
  };
  if (Array.isArray(dateRange.value) && dateRange.value.length === 2) {
    const [start, end] = dateRange.value as [string, string];
    params.startTime = start;
    params.endTime = end;
  }
  // 严格按API文档传参
  return params;
};



// 获取所有可用的设备型号（用于初始化下拉选项）
const fetchAllDeviceModels = async () => {
  const token = getToken?.() || "";
  const headers = { Authorization: `Bearer ${token}` };
  try {
    // 获取所有数据来收集设备型号（不分页，只获取第一页用于收集型号）
    const params = {
      page: 1,
      limit: 1000, // 获取更多数据来收集设备型号
      faultStatus: 0, // 获取所有状态的数据
    };
    
    const resp: any = await alertApi.getPage(params, headers as any);
    if (resp && resp.code === 0) {
      const list: any[] = resp.data?.list || resp.data?.items || [];
      const mapped = list.map(mapToAlertItem);
      
      // 收集所有可用的设备型号
      const products = Array.from(new Set(mapped.map(x => x.product).filter(Boolean))) as string[];
      products.forEach(product => {
        if (product && product.trim()) {
          allAvailableDeviceModels.value.add(product.trim());
        }
      });
      
      // 更新下拉选项
      deviceModelOptions.value = [
        { value: "All device model", label: "All device model" },
        ...Array.from(allAvailableDeviceModels.value).map(p => ({ value: p, label: p }))
      ];
    }
  } catch (e: any) {
    console.error("获取设备型号失败", e);
  }
};

// 拉取数据
const fetchAlerts = async () => {
  loading.value = true;
  errorMessage.value = "";
  const params = buildQueryParams();
  const token = getToken?.() || "";
  const headers = { Authorization: `Bearer ${token}` };
  try {
    const resp: any = await alertApi.getPage(params, headers as any);
    if (resp && resp.code === 0) {
      const list: any[] = resp.data?.list || resp.data?.items || [];
      const mapped = list.map(mapToAlertItem);
      // 后端是否区分进行中/历史，若无则按recoveryTime是否为空划分
      allAlerts.value = mapped;
      activeAlerts.value = mapped.filter(x => !x.recoveryTime);
      historicalAlerts.value = mapped.filter(x => x.recoveryTime);
      pagination.total = resp.data?.total || mapped.length;

      // 下拉选项已在初始化时设置，这里不再更新
      // 只累积新的设备型号到全局集合中（用于后续可能的扩展）
      const products = Array.from(new Set(mapped.map(x => x.product).filter(Boolean))) as string[];
      products.forEach(product => {
        if (product && product.trim()) {
          allAvailableDeviceModels.value.add(product.trim());
        }
      });
      return;
    }
    allAlerts.value = [];
    activeAlerts.value = [];
    historicalAlerts.value = [];
    pagination.total = 0;
  } catch (e: any) {
    console.error("获取告警数据失败", e);
    errorMessage.value = e?.message || "Network error";
    allAlerts.value = [];
    activeAlerts.value = [];
    historicalAlerts.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 仅按标签切换数据集；筛选交由后端完成
const filteredAlerts = computed(() => {
  switch (activeTab.value) {
    case "Active":
      return activeAlerts.value;
    case "Historical":
      return historicalAlerts.value;
    default:
      return allAlerts.value;
  }
});

// 由后端分页，直接返回当前列表
const displayedAlertList = computed(() => filteredAlerts.value);

// 不在前端计算总数

// Alert details dialog
const dialogVisible = ref(false);
const alertDetails = reactive<AlertItem>({
  id: "",
  alertCode: "",
  alertName: "",
  deviceName: "",
  sn: "",
  product: "",
  faultyModule: "",
  occurrences: 0,
  status: "active",
  occurrenceTime: "",
  recoveryTime: null,
  deviceModel: "",
  possibleReason: "",
  suggestions: []
});

// Methods
const resetFilters = () => {
  filters.alertCode = "";
  filters.systemId = "";
  filters.deviceModel = "All device model";
  dateRange.value = [];
  pagination.currentPage = 1;
};

const searchAlerts = () => {
  pagination.currentPage = 1;
  fetchAlerts();
};

const handleTabChange = (tab: string) => {
  pagination.currentPage = 1;
  fetchAlerts();
};

const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.currentPage = 1;
  fetchAlerts();
};

const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  fetchAlerts();
};

const showDetails = (row: AlertItem) => {
  // Set alert details based on selected row
  Object.assign(alertDetails, row);
  dialogVisible.value = true;
};

const handleClose = () => {
  dialogVisible.value = false;
};

onMounted(async () => {
  // 默认时间范围：最近一个月
  const end = new Date();
  const start = new Date();
  start.setMonth(start.getMonth() - 1);
  // 使用与 value-format 一致的字符串
  const pad = (n: number) => String(n).padStart(2, "0");
  const fmt = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
  dateRange.value = [fmt(start), fmt(end)];
  
  // 先获取所有可用的设备型号，然后获取告警数据
  await fetchAllDeviceModels();
  fetchAlerts();
});

// loading & error states
const loading = ref(false);
const errorMessage = ref("");
const retryFetch = () => {
  errorMessage.value = "";
  fetchAlerts();
};

</script>

<style lang="scss" scoped>
:deep(.alert-details-dialog) {
  max-height: 80vh;

  .el-dialog__body {
    max-height: calc(80vh - 120px);
    overflow-y: auto;
    padding: 20px;
  }
}
</style>
